//
//  LFHomeSearchViewController.m
//  LoveFruit
//
//  Created by 张令林 on 16/9/23.
//  Copyright © 2016年 张令林. All rights reserved.
//

#import "LFHomeSearchViewController.h"
#import "LFHomeHotSellCell.h"
#import "LFHotSellerModel.h"
#import "LFFoodDetailController.h"


static NSString *searchCellid = @"searchCellid";
static NSString *searchResultCellid = @"hotsellerCellid";

@interface LFHomeSearchViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>

@property (nonatomic,weak) UISearchBar *searchView;
@property (nonatomic,weak) UICollectionView *collectionView;
//存储历史数据的数组.数组中存储的是数组,有数字和宽度
@property (nonatomic,strong) NSMutableArray *historyDataArray;
//最下面部分添加一个collectionView用来展示查询出来的数据
@property (nonatomic,weak) UICollectionView *searchResultCollectionView;

//查询结果的数组
@property (nonatomic,strong) NSArray *searchResultArray;



@end

@implementation LFHomeSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //获取数据LFHomeSearchHistoryData
    self.historyDataArray = [[NSUserDefaults standardUserDefaults] objectForKey:LFHomeSearchHistoryData];


    //调用初始化方法
    [self setUpUI];
    //创建导航栏视图
    [self setNav];
    
}

#pragma mark - 初始化方法
- (void)setUpUI
{
//    self.view.backgroundColor = HMColor(255, 135, 116);
    self.view.backgroundColor = HMColor(200, 200, 200);

    //添加一个layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    layout.itemSize = CGSizeMake(80, 30);
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    //添加查询结果的layout
    UICollectionViewFlowLayout *layoutS = [[UICollectionViewFlowLayout alloc] init];
    layoutS.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    layoutS.itemSize = CGSizeMake(80, 30);
    layoutS.minimumLineSpacing = 10;
    layoutS.minimumInteritemSpacing = 10;

    //添加控件
    //中间的视图
    UIView *centerView = [[UIView alloc] init];
    centerView.backgroundColor = HMColor(215, 215, 215);
    [self.view addSubview:centerView];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"v2_my_serviceonline_icon"]];
    [centerView addSubview:imageView];
    UILabel *infoLabel = [UILabel labelWithText:@"查询历史" andTextColor:[UIColor whiteColor] andFontSize:14];
    [infoLabel sizeToFit];
    [centerView addSubview:infoLabel];
    UIButton *removeHistoryBtn = [UIButton buttonLRWithImgName:nil title:@"清空历史" color:[UIColor darkGrayColor] forSize:14 target:self action:@selector(removeHistoryBtnClick) forControlEvents:UIControlEventTouchUpInside];
    removeHistoryBtn.backgroundColor = LFBackColor;
    [removeHistoryBtn setCornerRadius:10 alpha:1];
    [centerView addSubview:removeHistoryBtn];
    
    //历史记录视图
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    collectionView.backgroundColor = LFBackColor;
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    //设置代理/数据源
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    //注册单元格
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:searchCellid];

    //查询结果视图
    UICollectionView *resultView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layoutS];
    resultView.backgroundColor = LFBackColor;
    [self.view addSubview:resultView];
    
    self.searchResultCollectionView = resultView;
    //设置代理/数据源
    resultView.delegate = self;
    resultView.dataSource = self;
    //注册单元格
    [resultView registerNib:[UINib nibWithNibName:@"LFHomeHotSellCell" bundle:nil] forCellWithReuseIdentifier:searchResultCellid];
    
    //历史记录上面的视图
    [centerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(64);
        make.left.right.offset(0);
        make.height.offset(40);
    }];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.offset(6);
        make.bottom.offset(-6);
        make.width.offset(40);
    }];
    [infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(imageView);
        make.left.equalTo(imageView.mas_right).offset(2);
    }];
    [removeHistoryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(8);
        make.right.bottom.offset(-8);
        make.width.offset(60);
    }];
    //历史信息的视图
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(centerView.mas_bottom);
        make.left.right.offset(0);
        make.height.offset(150);
    }];
    //查询结果的视图
    [resultView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(collectionView.mas_bottom);
        make.left.right.bottom.offset(0);
    }];
}
//设置导航栏
- (void)setNav
{
    //查询框
    UISearchBar *searchView = [[UISearchBar alloc] init];
    [self.view addSubview:searchView];
    searchView.delegate = self;
    self.searchView = searchView;
    self.navigationItem.titleView = searchView;
    //显示历史查询条件的按钮
//    UIBarButtonItem *btnItem = [UIBarButtonItem barButtonWithTitle:@"历史" image:nil style:UIBarButtonItemStylePlain target:self action:@selector(showHistorySearchString)];
    UIButton *button = [UIButton buttonLRWithImgName:nil title:@"历史" color:[UIColor whiteColor] forSize:14 target:self action:@selector(showHistorySearchString) forControlEvents:UIControlEventTouchUpInside];
    button.size = CGSizeMake(30, 30);
    [button setCornerRadius:15 alpha:1];
    [button setColorAlpha:0.5];
    
    UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = btnItem;
    
}
#pragma mark - 按钮点击的方法
//显示历史查询信息的方法
- (void)showHistorySearchString
{
    //更新布局
    [self.searchResultCollectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom);
        make.left.right.bottom.offset(0);
    }];
    [UIView animateWithDuration:1 animations:^{
        [self.view layoutIfNeeded];
    }];
    if (self.searchView.y < 150)
    {
        [SVProgressHUD showInfoWithStatus:@"查询历史已经显示在视图中"];
    }
}
#pragma mark - collection的代理和数据源方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (collectionView == self.collectionView)
    {
        self.navigationController.navigationBar.alpha = 1;
        //NSLog(@"%zd-----",self.historyDataArray.count);
        return self.historyDataArray.count;
    }else
    {
        return self.searchResultArray.count;
    }
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collectionView)
    {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:searchCellid forIndexPath:indexPath];
        [self setCell:cell count:indexPath.row];
        return cell;
    }else
    {
        LFHomeHotSellCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:searchResultCellid forIndexPath:indexPath];
//        cell.backgroundColor = [UIColor randomColor];
        cell.model = self.searchResultArray[indexPath.row];
        return cell;
    }
    
}
//设置大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collectionView)
    {
        NSArray *arr = self.historyDataArray[indexPath.row];
        CGFloat wid = [arr[1] doubleValue]+30;
        return CGSizeMake(wid, 30);
    }
    
    return CGSizeMake((collectionView.bounds.size.width * 0.5 - 15) , 280);
}
//设置cell
- (void)setCell:(UICollectionViewCell *)cell count:(NSInteger)count
{
    for (UIView *v in cell.contentView.subviews)
    {
        [v removeFromSuperview];
    }
    NSArray *arr = self.historyDataArray[count];
    NSString *title = arr[0];
    //添加label
    UILabel *label = [UILabel labelWithText:title andTextColor:[UIColor darkGrayColor] andFontSize:14];
    [label sizeToFit];
    [cell.contentView addSubview:label];

    //添加按钮
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    UIButton *button = [UIButton buttonLRWithImgName:nil title:@"x" color:[UIColor whiteColor] forSize:10 target:self action:@selector(removeCellBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = HMColor(200, 200, 200);
    button.size = CGSizeMake(15, 15);
    [button setTitle:@"x" forState:UIControlStateNormal];
    [button setCornerRadius:7.5 alpha:1];
    [cell.contentView addSubview:button];
    button.tag = count;
    [button addTarget:self action:@selector(removeCellBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.backgroundColor = HMColor(250, 250, 250);
    cell.layer.cornerRadius = 10;
    cell.layer.masksToBounds = YES;
    
    //设置布局
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cell);
        make.left.offset(5);
    }];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-3);
        make.top.offset(3);
        make.width.height.offset(15);
    }];
    
}
//cell点击的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collectionView)
    {
        NSString *str = self.historyDataArray[indexPath.row][0];
        [self searchResult:str];
    }else
    {
        LFHotSellerModel *productModel = self.searchResultArray[indexPath.row];
        LFFoodDetailController *detailVc = [[LFFoodDetailController alloc] init];
        detailVc.sellerModel = productModel;
        
        [UIView animateWithDuration:1 animations:^{
            self.view.alpha = 0;
            self.navigationController.navigationBar.alpha = 0;
        } completion:^(BOOL finished) {
            [self.navigationController pushViewController:detailVc animated:NO];
            self.view.alpha = 1;
            self.navigationController.navigationBar.alpha = 1;
        }];
        
    }
}

#pragma mark - Search的代理方法  查询历史的相关处理方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
    if (searchText.length == 0 )
    {
        //更新布局
        [self.searchResultCollectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.collectionView.mas_bottom);
            make.left.right.bottom.offset(0);
        }];
        
        [UIView animateWithDuration:0.5 animations:^{
            self.navigationController.navigationBar.alpha = 1;
            [self.view endEditing:YES];
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            [self.searchResultCollectionView reloadData];
        }];
    }
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //保存数据
    NSString *str = [searchBar text];
    //声明一个参数来比较数组中是否已经有这个值,默认为NO
    BOOL isContain = NO;
    UILabel *label = [[UILabel alloc] init];
    label.text = str;
    [label sizeToFit];
    
    NSMutableArray *tempArray = [NSMutableArray array];
    for (int i = 0; i < self.historyDataArray.count; i++)
    {
        [tempArray addObject:self.historyDataArray[i]];
        //添加的时候判断一下是否有重复
        NSArray *arr = self.historyDataArray[i];
        if ([str isEqualToString:arr[0]])
        {
            isContain = YES;
        }
    }
    //没有相同的菜把这个值存入
    if (isContain == NO)
    {
        [tempArray addObject:@[str,@(label.frame.size.width)]];
    }
    
    self.historyDataArray = tempArray;
    [[NSUserDefaults standardUserDefaults] setObject:tempArray forKey:LFHomeSearchHistoryData];
    //刷新布局
    [self.collectionView reloadData];
    
    //执行查询的方法
    [self searchResult:searchBar.text];
}
//删除cell的按钮的点击方法
- (void)removeCellBtnClick:(UIButton *)sender
{
    NSMutableArray *tempArray = [NSMutableArray array];
    for (int i = 0; i < self.historyDataArray.count; i++)
    {
        if (i != sender.tag)
        {
            [tempArray addObject:self.historyDataArray[i]];
        }
    }
    self.historyDataArray = tempArray;
    [[NSUserDefaults standardUserDefaults] setObject:tempArray forKey:LFHomeSearchHistoryData];
    //刷新布局
    [self.collectionView reloadData];
}
//清空查询历史
- (void)removeHistoryBtnClick
{
    if (self.historyDataArray == nil)
    {
        [SVProgressHUD showInfoWithStatus:@"没有需要清理的历史查询信息"];
        return;
    }
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:LFHomeSearchHistoryData];
    self.historyDataArray = nil;
    [SVProgressHUD showInfoWithStatus:@"已清除所有历史查询信息"];
    [self.collectionView reloadData];
}
#pragma mark - 查询的方法
- (void)searchResult:(NSString *)searchString
{
    //更新布局
    [self.searchResultCollectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(64);
        make.left.right.bottom.offset(0);
    }];
    //获取查询结果
    [self getSearchResult:searchString];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.searchResultCollectionView reloadData];
    }];
}
//根据字符串计算查询结果的方法
- (void)getSearchResult:(NSString *)searchString
{
    //计算出查询结果
    NSMutableArray *tempArray = [NSMutableArray array];
    for (LFHotSellerModel *model in self.allDataArray)
    {
        //获得查询的字符串
        if ([model.name containsString:searchString])
        {
            [tempArray addObject:model];
        }
    }
    self.searchResultArray = tempArray;
    if (!(self.searchResultArray.count > 0))
    {
        [SVProgressHUD showInfoWithStatus:@"没有相关的物品"];
    }else
    {
        [self.searchResultCollectionView reloadData];
    }
}

@end
